package com.qyhl.webtv.module_news.news.goodlife.detail;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NormalNewsBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/15.
 * 新趣汇详情
 */

@Route(path = ARouterPathConstant.GOOD_LIFE_DETAIL)
public class GoodLifeDetailActivity extends BaseActivity implements GoodLifeDetailContract.GoodLifeDetailView {
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.detail_title)
    TextView detailTitle;
    @BindView(R2.id.publishdate)
    TextView publishdate;
    @BindView(R2.id.publishhouse)
    TextView publishhouse;
    @BindView(R2.id.author)
    TextView author;
    @BindView(R2.id.info_layout)
    RelativeLayout infoLayout;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.webview)
    WebView webview;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.scan)
    TextView scan;

    private GoodLifeDetailPresenter mPresenter;
    @Autowired(name = "newsId")
    String newsId;
    private NormalNewsBean mBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_goodlife_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new GoodLifeDetailPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.count(newsId);
        mPresenter.getData(newsId);
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        shareBtn.setEnabled(false);//加载中禁止分享

        //点击水波纹效果
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            shareBtn.setBackgroundResource(R.drawable.news_center_item_ripple);
            back.setBackgroundResource(R.drawable.news_center_item_ripple);
        }

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //分享
        shareBtn.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(GoodLifeDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                if (mBean != null) {
                    MShareBoard shareBoard = new MShareBoard(GoodLifeDetailActivity.this, newsId, mBean.getTitle(), mBean.getLogo(), mBean.getSummary(), 5, true);
                    shareBoard.showPopupWindow();
                } else {
                    Toasty.normal(GoodLifeDetailActivity.this, "请等待信息加载...", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(GoodLifeDetailActivity.this);
            }
        }));

        //返回
        back.setOnClickListener(v -> finish());

        //重新加载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getData(newsId);
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 设置数据
     *
     * @param bean
     */
    @Override
    public void setData(NormalNewsBean bean) {
        mBean = bean;
        //标题
        detailTitle.setText(mBean.getTitle());

        //发布日期
        if (StringUtils.isNotEmpty(mBean.getPublishDate())) {
            publishdate.setVisibility(View.VISIBLE);
            publishdate.setText(DateUtils.originFormat(mBean.getPublishDate()));
        } else {
            publishdate.setVisibility(View.GONE);
        }

        //浏览数
        scan.setText(mBean.getHitCount());

        //摘要
        if (StringUtils.isNotEmpty(mBean.getSummary())) {
            summary.setVisibility(View.VISIBLE);
            summary.setText(mBean.getSummary());
        } else {
            summary.setVisibility(View.GONE);
        }

        //来源
        if (StringUtils.isNotEmpty(mBean.getReferName())) {
            publishhouse.setVisibility(View.VISIBLE);
            publishhouse.setText(mBean.getReferName());
        } else {
            publishhouse.setVisibility(View.GONE);
        }

        //作者
        if (StringUtils.isNotEmpty(mBean.getWriter())) {
            author.setVisibility(View.VISIBLE);
            author.setText(mBean.getWriter());
        } else {
            author.setVisibility(View.GONE);
        }

        //webview
        String mContent = mBean.getContent();
        mContent = "<html><head></head><body>" + mContent + "</body></html>";
        if (mContent.indexOf("<!--PLAYERCODESTART-->") != -1) {
            mContent = mContent.replace(mContent.substring(mContent.indexOf("<!--PLAYERCODESTART-->"), mContent.indexOf("<!--PLAYERCODEEND-->") + 20), "");
        }
        showContent(mContent);
    }

    //展示内容
    private void showContent(String content) {
        initWebView();
        webview.setWebViewClient(new MyWebViewClient());
        webview.loadDataWithBaseURL(null, getNewContent(content), "text/html", "utf-8", null);
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");
        }
        return doc.toString();
    }

    //初始化webview
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(false);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    }

    //Web视图
    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                Uri uri = Uri.parse(url); // url为你要链接的地址
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            loadMask.setStatus(LoadingLayout.Success);
            loadMask.setReloadButtonText("点击重试~~");
            shareBtn.setEnabled(true);
        }
    }

    /**
     * 网络出错
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }


    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack(); //goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("新趣汇详情");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.GOODLIFEDETAIL);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //5.0以下reload会白屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (webview != null) {
                webview.reload();
            }
        }
        //baidu
        //umeng
        MobclickAgent.onPageEnd("新趣汇详情");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.GOODLIFEDETAIL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.removeAllViews();
            webview.destroy();
        }
    }


}
